import Vue from 'vue'
import store from '../../store/index.js'
import {
	HttpWidget,
	Http
} from '../dt-request'

const rmCache = (key) => {
	let app_data = uni.getStorageSync('app_data')
	if (!app_data) app_data = new Object()
	delete app_data[key]
	uni.setStorageSync('app_data', app_data)
}
const setCache = (key, data, expire_time) => {
	let app_data = uni.getStorageSync('app_data')
	if (!app_data) app_data = new Object()
	if (expire_time > 0) {
		let timestamp = (new Date()).valueOf()
		expire_time = timestamp + expire_time * 1000
	} else expire_time = 0
	app_data[key] = {
		data: data,
		expire_time: expire_time
	}
	uni.setStorageSync('app_data', app_data)
}
const getCache = (key) => {
	let app_data = uni.getStorageSync('app_data')
	if (app_data[key]) {
		let timestamp = (new Date()).valueOf()
		if (app_data[key]['expire_time'] == 0 || app_data[key]['expire_time'] > timestamp) {
			return app_data[key]['data']
		}
	}
	return null
}
const showSuccess = (msg, callback, delayed) => {
	uni.showToast({
		icon: 'success',
		title: msg,
		success() {
			callback && (setTimeout(() => {
				callback()
			}, 2500))
		}
	})
}

const showError = (msg, callback) => {
	uni.showToast({
		icon: 'none',
		title: msg,
		success() {
			callback && (setTimeout(() => {
				callback()
			}, 1500))
		}

	})
}

const showErrorModal = (error) => {
	uni.showModal({
		title: '出错了',
		content: error,
		showCancel: true,
		cancelText: '返回',
		confirmText: '首页',
		success(res) {
			if (res.confirm) {
				uni.navigateTo({
					url: "/"
				})
			} else {
				uni.navigateBack()
			}
		}
	})
}

const timeFormat = (arg, type) => {
	if (!arg) return ''
	if (!type)
		type = 'YYYY-MM-DD h:m:s'

	if (arg.toString().length == 10) {
		arg = arg * 1000;
		//如果date为13位不需要乘1000
		//[js时间戳长度是13位]，php，java等时间戳长度为10位
	}
	var date = new Date(arg)
	var year = date.getFullYear(); //获取年
	var mouth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1); //月
	var day = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()); //日
	var hour = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()); //时
	var minute = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()); //分
	var second = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()); //秒
	var week; //星期
	if (date.getDay() == 0) week = "星期日"
	if (date.getDay() == 1) week = "星期一"
	if (date.getDay() == 2) week = "星期二"
	if (date.getDay() == 3) week = "星期三"
	if (date.getDay() == 4) week = "星期四"
	if (date.getDay() == 5) week = "星期五"
	if (date.getDay() == 6) week = "星期六"
	if (type == 'YYYY-MM-DD h:m:s') {
		return year + '-' + mouth + '-' + day + ' ' + hour + ':' + minute + ':' + second;
	}
	if (type == 'YYYY-MM-DD') {
		return year + '-' + mouth + '-' + day;
	}
	if (type == 'MM-DD') {
		return mouth + '-' + day;
	}
	if (type == 'MM-DD WEEK') {
		return mouth + '-' + day + ' ' + week;
	}
	if (type == 'h:m:s') {
		return hour + ':' + minute + ':' + second
	}
	if (type == 'h:m') {
		return hour + ':' + minute
	}
}

const getImUsername = () => {
	let u = uni.getStorageSync("username");

	if (u) {
		return u;
	} else {
		let l = uni.getStorageSync("__IM_LOGIN_USERNAME");
		let user = JSON.parse(l)
		uni.setStorageSync("username", user.im);

		return user.im;
	}
}

const saveCode = (params) => {
	let code = params.code
	if (code) uni.setStorageSync('su_code', code)
}

const setBackUrl = () => {
	let pages = getCurrentPages()
	let curPage = pages[pages.length - 1]
	// console.log(curPage)

	let q = new Array()
	for (var i in curPage.options) {
		q.push(i + '=' + curPage.options[i])
	}

	let backurl = '/' + curPage.route + '?' + q.join('&')
	// console.log(backurl)
	setCache('backurl', backurl)
}

/**
 * 验证登录权限
 */
const loginAuth = (back) => {
	if (!store.state.hasLogin) {
		if (back) {
			setBackUrl()
			showError('请登录后再操作', (res) => {
				uni.redirectTo({
					url: "/pages/site/login"
				})
			})
		} else {
			showError('请登录后再操作', (res) => {
				uni.navigateBack({})
			})
		}
		return false
	} else
		return true
}

const getIndex = (page_code) => {
	let page_data = getCache('page-' + page_code);
	if (page_data) {
		return new Promise((resolve, reject) => {

			// 伪造成功，历史代码保存结果
			resolve({
				data: {
					data: page_data
				}
			});
		});
	}

	let http = new Http()
	return http.get('pages', {
		code: page_code
	})
		.then((response) => {

			setCache('page-' + page_code, response.data.data, 10 * 60)
			uni.setStorageSync('theme_default', response.data.data.style);

			uni.hideLoading();

			return response;
		})
		.catch((response) => {
			console.log('获取首页报错');
			console.log(response);
			uni.hideLoading()
		})
}

/**
 * 验证模块权限
 */
const moduleAuth = (module) => {
	return new Promise((resolve, reject) => {
		resolve()
		// getConfig().then(function(response) {
		// 	let config = response
		// 	if (config.module.indexOf(module) >= 0) {
		// 		resolve()
		// 	} else {
		// 		uni.showModal({
		// 			title: '权限有误',
		// 			content: '模块权限有误，请浏览其他模块',
		// 			showCancel: true,
		// 			cancelText: '返回',
		// 			confirmText: '个人中心',
		// 			success(res) {
		// 				if (res.confirm) {
		// 					uni.navigateTo({
		// 						url: "/pages/member/index"
		// 					})
		// 				} else {
		// 					uni.navigateBack()
		// 				}
		// 			}
		// 		})
		// 		reject()
		// 	}
		// }).catch(function(res) {
		// 	reject(res)
		// })
	})
}

/**
 * 获取服务器配置
 */
const getConfig = () => {
	return new Promise((resolve, reject) => {
		let config = getCache('config')
		if (!config) {
			let http = new Http()
			http.get('config', {
				group: 'mini-program'
			})
				.then((response) => {
					setCache('config', response.data.data, 30 * 60)
					resolve(response.data.data)
				})
				.catch((response) => {
					reject(response)
				})
		} else {
			resolve(config)
		}
	})
}
/**
 * 购物车数量
 */
const getCartNum = () => {
	return new Promise((resolve, reject) => {
		let cart_num = getCache('cart_num')
		if (!cart_num) {
			let http = new Http()
			http.get('card_count')
				.then((response) => {
					setCache('cart_num', response.data.data, 10 * 60)
					resolve(response.data.data)
				})
				.catch((response) => {
					reject(response)
				})
		} else {
			resolve(cart_num)
		}
	})
}
/**
 * 通知数量
 */
const getNotifyNum = () => {
	return new Promise((resolve, reject) => {
		let notice_count = getCache('notice_count')
		if (!notice_count) {
			let http = new Http()
			http.get('notice_count')
				.then((response) => {
					setCache('notice_count', response.data.data, 1 * 60)
					resolve(response.data.data)
				})
				.catch((response) => {
					reject(response)
				})
		} else {
			resolve(notice_count)
		}
	})
}
/**
 * 我的信息
 */
const getMember = () => {
	return new Promise((resolve, reject) => {
		let config = getCache('member')
		if (!config) {
			uni.showLoading({
				title: '加载中...'
			})
			let http = new Http()
			http.get('member_my', {})
				.then((response) => {
					setCache('member', response.data.data, 2 * 60)
					uni.hideLoading()
					resolve(response.data.data)
				})
				.catch((response) => {
					uni.hideLoading()
					reject(response)
				})
		} else {
			resolve(config)
		}
	})
}

const mathRichText = (content) => {
	return content.replace(/<img/gi, '<img style="max-width:100%;height:auto;float:left;display:block" ')
}

const setTitle = (web_site_title) => {
	return uni.setNavigationBarTitle({
		title: web_site_title
	});
}

const changePhone = (num, len=4)=>{
	if(String(num).indexOf("*") == -1){
		return String(num).substr(0,3)+"****"+String(num).substr(7);
	}
	return num;
}

export default {
	getIndex,
	getConfig,
	getCartNum,
	getNotifyNum,
	loginAuth,
	moduleAuth,
	rmCache,
	setCache,
	getCache,
	showSuccess,
	showError,
	timeFormat,
	getImUsername,
	saveCode,
	getMember,
	showErrorModal,
	setBackUrl,
	mathRichText,
	setTitle,
	changePhone,
}
